package com.cgsd.heyu.ui.task;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.utils.LogUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiConfig;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.AvatarManger;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.common.Helper;
import com.cgsd.heyu.entity.EventMessage;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.presenter.BasePresenter;
import com.cgsd.heyu.ui.BasePickerActivity;
import com.cgsd.heyu.ui.task.adapter.DoStepAdapter;
import com.cgsd.heyu.ui.task.vo.DoTaskDetailVo;
import com.cgsd.heyu.ui.task.vo.UploadVo;
import com.cgsd.heyu.utils.ImagePreviewActivity;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/3 10:19
 * Email: xcode126@126.com
 * Desc: 我的任务-待提交
 */
public class TaskCommitActivity extends BasePickerActivity<BasePresenter> implements View.OnClickListener {

    private TextView tvStatus;
    private ShapeableImageView imageView;
    private TextView tvName;
    private TextView tvLabel1;
    private TextView tvLabel2;
    private TextView tvCommitTime;
    private TextView tvAmount;
    private TextView tvV;

    private RecyclerView mRecyclerView;
    private TextView tvCommit;

    private int tid;
    private DoStepAdapter stepAdapter;
    private int currentPosition;

    public static Intent getIntent(Context context, int tid) {
        return new Intent(context, TaskCommitActivity.class).putExtra("tid", tid);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_commit;
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullBar(this);
    }

    @Override
    protected void initView() {
        tid = getIntent().getIntExtra("tid", 0);
        bindViews();

        initAdapter();
    }

    @Override
    protected void initData() {
        doTaskDetail();
    }

    /**
     * bind views
     */
    private void bindViews() {
        tvStatus = findViewById(R.id.tv_status);
        imageView = findViewById(R.id.iv_bg);
        tvName = findViewById(R.id.tv_name);
        tvLabel1 = findViewById(R.id.tv_label1);
        tvLabel2 = findViewById(R.id.tv_label2);
        tvCommitTime = findViewById(R.id.tv_commit_time);
        tvAmount = findViewById(R.id.tv_amount);
        tvV = findViewById(R.id.tv_v);

        mRecyclerView = findViewById(R.id.mRecyclerView);
        tvCommit = findViewById(R.id.tv_commit);
        findViewById(R.id.tv_commit).setOnClickListener(this);
    }

    /**
     * init adapter
     */
    private void initAdapter() {
        stepAdapter = new DoStepAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(stepAdapter);
        mRecyclerView.setNestedScrollingEnabled(false);
        stepAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            DoTaskDetailVo.InfoBean.StepBean item = stepAdapter.getItem(position);
            switch (view.getId()) {
                case R.id.iv_picture:
                    if (TextUtils.isEmpty(item.imagePath)) {
                        currentPosition = position;
                        showPictureSelector(1, true, true);
                    } else {
                        ArrayList<String> list = new ArrayList<>();
                        list.add(item.imagePath);
                        startActivity(ImagePreviewActivity.getIntent(this, list, 0));
                    }
                    break;
                case R.id.iv_close:
                    item.imagePath = "";
                    stepAdapter.notifyItemChanged(position);
                    break;
                case R.id.rl_example:
                    ArrayList<String> list = new ArrayList<>();
                    list.add(item.image);
                    startActivity(ImagePreviewActivity.getIntent(this, list, 0));
                    break;
            }

        });
    }

    /**
     * do task
     */
    private void doTaskDetail() {
        showLoading();
        RequestBody requestBody = new RequestParams()
                .putUid()
                .put("tid", tid)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .doTaskDetail(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<DoTaskDetailVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<DoTaskDetailVo> baseResponse) {
                        com.apkfuns.logutils.LogUtils.e(TAG + baseResponse.getBizBody().toString());
                        processDoTaskDetail(baseResponse.getBizBody());
                        loadSuccess();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        com.apkfuns.logutils.LogUtils.e(TAG + error.getBody().toString());
                        loadSuccess();
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * process do task detail
     * 0待完成对应按钮是：立即提交；1已提交对应按钮：提交修改
     *
     * @param detailVo
     */
    private void processDoTaskDetail(DoTaskDetailVo detailVo) {
        tvStatus.setText(detailVo.statetext);
        handleBtnState(detailVo);

        DoTaskDetailVo.InfoBean info = detailVo.info;
        if (info != null) {
            AvatarManger.setAvatar(this, info.gender, imageView);
            tvName.setText(info.title);
            tvLabel1.setText("标签一");
            tvLabel2.setText("标签二");
            tvCommitTime.setText(Html.fromHtml(String.format("%1$s<font color ='#666666'>%2$s%3$s</font>", getString(R.string.a_commit_), info.finish, getString(R.string.a_unit_hour))));
            tvAmount.setText(String.format("%1$s%2$.2f%3$s", getString(R.string.a_reward_), info.price1, getString(R.string.a_unit_yuan)));
            tvV.setText(String.format(String.format("%1$s%2$.2f%3$s", "V：", info.price, getString(R.string.a_unit_yuan))));
            if (info.step != null && info.step.size() > 0) {
                for (DoTaskDetailVo.InfoBean.StepBean stepBean : info.step) {
                    DoTaskDetailVo.InfoBean.DostepBean doStep = getDoStep(info, stepBean.step);
                    if (doStep != null) {
                        stepBean.imagePath = doStep.backiimage;
                        stepBean.inputText = doStep.backcom;
                    }
                }
            }
            stepAdapter.setNewData(info.step);
        }
    }

    /**
     * 处理按钮的状态
     * 0=待完成,1=已提交,2=通过,3=驳回,-1=过期
     *
     * @param detailVo
     */
    private void handleBtnState(DoTaskDetailVo detailVo) {
        tvCommit.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(detailVo.state)) {
            switch (detailVo.state) {
                case "0":
                    tvCommit.setText("立即提交");
                    tvCommit.setVisibility(View.VISIBLE);
                    break;
                case "3":
                    tvCommit.setText("提交修改");
                    tvCommit.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    /**
     * 通过step获取已经完成的对应的step数据
     *
     * @param info
     * @param step
     * @return
     */
    private DoTaskDetailVo.InfoBean.DostepBean getDoStep(DoTaskDetailVo.InfoBean info, int step) {
        if (info.dostep != null && info.dostep.size() > 0) {
            for (DoTaskDetailVo.InfoBean.DostepBean dostepBean : info.dostep) {
                if (dostepBean.step == step) {
                    return dostepBean;
                }
            }
        }
        return null;
    }

    /**
     * commit task
     *
     * @param taskdata
     */
    private void commitTask(String taskdata) {
        showCommonSubmitDialog();
        RequestBody requestBody = new RequestParams()
                .putUid()
                .put("tid", tid)
                .put("taskdata", taskdata)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .commitTask(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                    @Override
                    public void onSuccess(BaseResponse<Void> baseResponse) {
                        processCommitTask(baseResponse.getCode(), baseResponse.getResultMsg());
                        dismissCommonSubmitDialog();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                    }
                });
//        OkGo.<String>post(ApiService.BASE_PHP_URL + "/" + ApiConfig.API_COMMIT_TASK)
//                .tag(this)
//                .params("tid", tid)
//                .params("taskdata", taskdata)
//                .headers("token", Helper.getTokenPhpInfo())
////                .isMultipart(true)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        try {
//                            UploadVo uploadVo = new Gson().fromJson(response.body(), UploadVo.class);
//                            LogUtils.i("sky", "上传图片返回：" + response.body());
//                            DoTaskDetailVo.InfoBean.StepBean item = stepAdapter.getItem(currentPosition);
//                            item.imagePath = uploadVo.bizBody.fullurl;
//                            stepAdapter.notifyDataSetChanged();
//                        } catch (Exception e) {
//                            showToast("解析数据异常，请稍后重试");
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        showToast("操作异常，请稍后重试");
//                    }
//                });
    }

    /**
     * process commit task
     *
     * @param code
     */
    private void processCommitTask(int code, String msg) {
        if (code == 200) {
            showToast(msg);
            EventBus.getDefault().post(new EventMessage<>(Constants.EventCode.TASK_REFRESH));
            finish();
        } else {
            showToast("操作失败，请稍后重试");
        }
    }

    /**
     * upload file
     *
     * @param path
     */
    public void uploadFile(String path) {
        File file = new File(path);
        OkGo.<String>post(AppConfig.BASE_PHP_URL + "/" + ApiConfig.API_UPLOAD_FILE)
                .tag(this)
                .params("file", file)
                .headers("token", Helper.getTokenPhpInfo())
                .isMultipart(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            UploadVo uploadVo = new Gson().fromJson(response.body(), UploadVo.class);
                            LogUtils.i("sky", "上传图片返回：" + response.body());
                            DoTaskDetailVo.InfoBean.StepBean item = stepAdapter.getItem(currentPosition);
                            item.imagePath = uploadVo.bizBody.fullurl;
                            stepAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            showToast("解析数据异常，请稍后重试");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        showToast("操作异常，请稍后重试");
                    }
                });

    }

    @Override
    public void onClick(View view) {
        String param = stepAdapter.getParam();
        if (TextUtils.isEmpty(param)) {
            showToast("请先按照任务要求操作");
            return;
        }
        LogUtils.i("sky", param);
        commitTask(param);
    }

    @Override
    public void obtainMediaResult(List<LocalMedia> list, int type) {
        if (list != null && list.size() > 0) {
            LocalMedia localMedia = list.get(0);
            String path = localMedia.getCompressPath();
            if (TextUtils.isEmpty(path)) {
                showToast("照片路径为空");
                return;
            }
            uploadFile(path);
        }
    }
}
